/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.hazardsource.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.hazardsource.domain.HiddenDanger;
import com.koron.hazardsource.domain.IndicationItems;
import com.koron.hazardsource.domain.IndicationType;
import com.koron.hazardsource.mapper.HiddenDangerMapper;
import com.koron.hazardsource.service.api.HiddenDangerService;
import com.koron.hazardsource.service.api.IndicationTypeService;
import com.koron.hazardsource.util.BusinessCode;
import com.koron.hazardsource.util.Immutable;
import com.koron.system.domain.DictData;
import com.koron.system.service.api.DictDataService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.InputStream;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@PropertySource({ "classpath:flow.properties" })
public class HiddenDangerServiceImpl implements HiddenDangerService,AfterApprovalService,InitializingBean {
	private final static Logger logger = LoggerFactory.getLogger(HiddenDangerServiceImpl.class);
	@Autowired
	private FlowManagement flowManagement;
	
	@Value("${safe_standard_hd_add}")
	private String safe_standard_hd_add;
	
	@Value("${safe_standard_hd_update}")
	private String safe_standard_hd_update;
	
	@Value("${safe_standard_hd_discard}")
	private String safe_standard_hd_discard;
	
	@Value("${flow.standard.setCode}")
    private String setCode;
	
	@Autowired
    private DictDataService dataService;
	
	@Autowired
    private FastDFSClientWrapper clientWrapper;
	
	@Autowired
    private IndicationTypeService indicationTypeService;
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void afterPropertiesSet() throws Exception {
		Map map = flowManagement.getHandlers();
		map.put(HiddenDanger.class.getName(), this);
		
	}
	
	
	
	@Override
	public void processDiscard(Audit audit) {
		// TODO Auto-generated method stub
		
	}



	@SuppressWarnings("deprecation")
	@Override
	public void editApproval(Audit audit) {
		List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
		try(SessionFactory factory=new SessionFactory()){
			HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
			List<HiddenDanger> beanList = mapper.queryListById("hidden_danger_history", idList);
			save(beanList);
			mapper.updateFstatusflag(idList, 2);
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public void discardApproval(Audit audit) {
		List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
		try(SessionFactory factory=new SessionFactory()){
			HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
			List<HiddenDanger> beanList = mapper.queryListById("hidden_danger_history", idList);
			List<String> codeList = beanList.stream().map(HiddenDanger::getCode).collect(Collectors.toList());
			mapper.updateState(codeList, 0);
		}
	}

	
	
	@SuppressWarnings("deprecation")
	@Override
	public List<HiddenDanger> queryList(String name, String dangerTypeId, String dangerLevelId, String firstElementId,
			String secondElementId, String description, Integer state, Integer page, Integer pageSize) {
		Integer start = null;
	    Integer end = null;
		if (null!=page && pageSize!=null){
            if (page >0 && pageSize > 0){
            }else{
            	//第一页 10条数据
            	page =1;
            	pageSize=10;
            }
            start=(page<=1)?0:(page-1)*pageSize;
            end = pageSize;
        }
		List<HiddenDanger> list = new ArrayList<>();
		try(SessionFactory factory=new SessionFactory()) {
			HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
			list = mapper.list(name, dangerTypeId, 
		    		dangerLevelId, firstElementId, secondElementId, description, state, start,end);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		return list;
	}

	@SuppressWarnings("deprecation")
	@Override
	public MessageBean<List<HiddenDanger>> queryByDescription(String description) {
		MessageBean<List<HiddenDanger>> msg=new MessageBean<>();
		try(SessionFactory factory=new SessionFactory()){
			List<HiddenDanger> list=factory.getMapper(HiddenDangerMapper.class).queryByDescription(description);
			msg.setData(list);
			msg.setCode(BusinessCode.MESSAGE_CODE_SUCCESS);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SUCCESS);
			return msg;
		}
	}

	@SuppressWarnings({ "rawtypes", "deprecation", "unchecked" })
	@Override
	public MessageBean<?> list(String name, String dangerTypeId, String dangerLevelId, String firstElementId,
			String secondElementId, String description, Integer state, Integer page, Integer pageSize) {
		MessageBean<DataBean> msg= MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, DataBean.class);
		Integer totalPage = null;
	    Integer totalNumber = null;
	    Integer start = null;
	    Integer end = null;
	    try(SessionFactory factory=new SessionFactory()){
	    	if (null!=page && pageSize!=null){
	            if (page >0 && pageSize > 0){
	            }else{
	            	//第一页 10条数据
	            	page =1;
	            	pageSize=10;
	            }
	            start=(page<=1)?0:(page-1)*pageSize;
	            end = pageSize;
	        }
	    	HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
		    List<HiddenDanger> list = mapper.list(name, dangerTypeId, 
		    		dangerLevelId, firstElementId, secondElementId, description, state, start,end);
		    totalNumber = mapper.count(name, dangerTypeId, dangerLevelId, firstElementId, secondElementId, description, state);
		    if(start != null && end != null){
				totalPage = totalNumber/pageSize+1;
			}else{
				totalPage = 1;
				page = totalPage;
				pageSize = totalNumber;
			}
		    DataBean data = new DataBean();
			data.setList(list);
			data.setPageNo(page);
			data.setPageSize(pageSize);
			data.setTotalNumber(totalNumber);
			data.setTotalPage(totalPage);
			msg.setData(data);
	    }catch (Exception e) {
	    	msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
			return msg;
		}
		return msg;
	}
	
	@SuppressWarnings({ "rawtypes", "deprecation" })
	@Override
	public MessageBean<?> getDraftList(StaffBean user) {
		MessageBean<List> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, List.class);
		try(SessionFactory factory=new SessionFactory();){
			HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
			List<HiddenDanger> list = mapper.getDraftList(user.getCode());
			msg.setData(list);
		}catch (Exception e) {
    		msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
		}
		return msg;
	}



	@SuppressWarnings({ "deprecation" })
	public void save(List<HiddenDanger> beanList){
		try(SessionFactory factory=new SessionFactory()){
			HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
			Date date = new Date();
			for (HiddenDanger bean : beanList) {
				String oldId = bean.getId();
				String code = bean.getCode();
				bean.setState(1);
				bean.setFstatusflag(2);
				if(StringUtils.isEmpty(code)){
					bean.setId(DefaultIdGenerator.getInstance().generateLongId());
					bean.setAddTime(date);
					bean.setCode(generateCode(factory));
					mapper.insert("hidden_danger", bean);
					mapper.updateCode(oldId, bean.getCode());
				}else{
					HiddenDanger hd = mapper.queryOneByCode(code);
					if(hd == null){
						bean.setId(DefaultIdGenerator.getInstance().generateLongId());
						bean.setAddTime(date);
						bean.setCode(generateCode(factory));
						mapper.insert("hidden_danger", bean);
						mapper.updateCode(oldId, bean.getCode());
					}else{
						bean.setId(hd.getId());
						bean.setUpdateTime(date);
						mapper.update("hidden_danger", bean);
					}
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}
	
	@SuppressWarnings({ "unchecked","rawtypes" })
	private Map addCheck(List<HiddenDanger> beanList) {
        Map map = new HashMap();
        for (HiddenDanger hd : beanList) {
            if (null == hd) {
                map.put("code", 22001);
                map.put("description", "未填写隐患信息");
                return map;
            }
            //校验隐患的字段
            if (StringUtils.isEmpty(hd.getDescription())) {
                map.put("code", 22001);
                map.put("description", "隐患描述不能为空");
                return map;
            }
            if (null == hd.getDangerTypeId()) {
                map.put("code", 22001);
                map.put("description", "隐患类型不能为空");
                return map;
            }
            if (null == hd.getDangerLevelId()) {
                map.put("code", 22001);
                map.put("description", "隐患分级不能为空");
                return map;
            }
            if (null == hd.getFirstElementId()) {
                map.put("code", 22001);
                map.put("description", "要素一级分类不能为空");
                return map;
            }
            if (null == hd.getSecondElementId()) {
                map.put("code", 22001);
                map.put("description", "要素二级分类不能为空");
                return map;
            }
        }
        map.put("code", 0);
        map.put("description", "校验成功");
        return map;
    }
	
	
	
	@SuppressWarnings({ "deprecation", "rawtypes" })
	@Override
	public MessageBean<?> saveDraft(List<HiddenDanger> beanList, StaffBean user) {
		MessageBean<List> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, List.class);
		
		//新增校验
        Map checkMap = addCheck(beanList);
        int code = (int) checkMap.get("code");
        String description = (String) checkMap.get("description");
        if (code != 0) {
            msg.setCode(code);
            msg.setDescription(description);
            return msg;
        }
		try(SessionFactory factory=new SessionFactory()){
			List<String> idList = new ArrayList<String>();
			HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
			Date date = new Date();
			for (HiddenDanger bean : beanList) {
				bean.setFstatusflag(0);
				bean.setAddTime(date);
				bean.setAddUser(user.getCode());
				bean.setAddUserName(user.getName());
				bean.setUpdateTime(date);
				bean.setUpdateUser(user.getCode());
				bean.setUpdateUserName(user.getName());
				if(bean.getState() == null){
					bean.setState(1);
				}
				String id = bean.getId();
				if(StringUtils.isEmpty(id)){
					id = DefaultIdGenerator.getInstance().generateLongId();
					bean.setId(id);
					mapper.insert("hidden_danger_history", bean);
				}else{
					mapper.update("hidden_danger_history", bean);
				}
				idList.add(id);
			}
			if(idList.isEmpty()){
				msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
				msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
				return msg;
			}
			msg.setData(idList);
			return msg;
		}catch (Exception e) {
	    	msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
			return msg;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public MessageBean<?> submit(List<HiddenDanger> beanList, StaffBean user, String title, String note) {
		MessageBean<?> msg = saveDraft(beanList, user);
		try{
			List<String> idList = new ArrayList<String>();
			if(msg.getData() != null){
				idList = (List<String>) msg.getData();
			}else{
				return msg;
			}
			//启动流程
			Audit audit = new Audit(title, note, user.getName(), new Date());
			audit.setId(DefaultIdGenerator.getInstance().generateLongId());
			audit.setTitle(title);
			audit.setDescription(note);
			audit.setInitiatorCode(user.getCode());
			audit.setTarget(HiddenDanger.class.getName());
			audit.setSetCode(setCode);
			audit.setTemplateKey(safe_standard_hd_add);
			audit.setOperation(1);
			audit.setState(1);
			audit.setFlowType(1);
			audit.setFlowName(Immutable.ADD_HIDDEN_DANGER);
			audit.setBusinessIds(new Gson().toJson(idList));
			if(!flowManagement.initFlow(user, audit, new HashMap<>())){
				msg.setCode(BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
				msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
				return msg;
			}
			updateFstatusflag(idList, 1);
		}catch(Exception e){
			msg.setCode(BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
		}
		return msg;
	}
	
	@SuppressWarnings("deprecation")
	public void updateFstatusflag(List<String> idList, int fstatusflag) {
        try (SessionFactory factory = new SessionFactory();) {
        	HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
        	mapper.updateFstatusflag(idList, fstatusflag);
        } catch (Exception e) {
			logger.error(e.getMessage(),e);
        }
    }
	
	@SuppressWarnings("deprecation")
	public void updateState(List<String> codeList, int state) {
        try (SessionFactory factory = new SessionFactory();) {
        	HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
        	mapper.updateState(codeList, state);
        } catch (Exception e) {
			logger.error(e.getMessage(),e);
        }
    }
	
	@SuppressWarnings({ "deprecation" })
	@Override
	public MessageBean<?> discard(List<String> idList, StaffBean user,String title, String note) {
		MessageBean<?> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, void.class);
		try(SessionFactory factory=new SessionFactory()){
			HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
			List<HiddenDanger> hdList = mapper.queryListById("hidden_danger", idList);
			if(hdList.isEmpty()){
				msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
				msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
				factory.close(false);
				return msg;
			}
			idList = new ArrayList<String>();
			for (HiddenDanger hd : hdList) {
				String id = DefaultIdGenerator.getInstance().generateLongId();
				hd.setState(0);
				hd.setId(id);
				idList.add(id);
			}
			mapper.batchInsert("hidden_danger_history", hdList);
			//启动流程
			Audit audit = new Audit(title, note, user.getName(), new Date());
    		audit.setId(DefaultIdGenerator.getInstance().generateLongId());
    		audit.setTitle(title);
    		audit.setDescription(note);
    		audit.setInitiatorCode(user.getCode());
    		audit.setTarget(HiddenDanger.class.getName());
    		audit.setSetCode(setCode);
    		audit.setTemplateKey(safe_standard_hd_discard);
    		audit.setOperation(2); //废弃
    		audit.setState(1);
    		audit.setFlowType(1);
    		audit.setFlowName(Immutable.DISCARD_HIDDEN_DANGER);
			audit.setBusinessIds(new Gson().toJson(idList));
			if(flowManagement.initFlow(user, audit, new HashMap<>())){
				factory.close();
			}else{
				msg.setCode(BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
				msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
				factory.close(false);
			}
			return msg;
		} catch (Exception e) {
			msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
			return msg;
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public HiddenDanger details(String tableName, String id) {
		try(SessionFactory factory=new SessionFactory()){
			return factory.getMapper(HiddenDangerMapper.class).queryById(tableName, id);
		}
	}
	
	
	@SuppressWarnings("deprecation")
	@Override
	public MessageBean<?> deleteDraft(String id) {
		MessageBean<?> msg = MessageBean.create(0, "success", void.class);
		SessionFactory factory = new SessionFactory();
        try{
        	HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
        	mapper.deleteDraft(id);
			factory.close();
        } catch (Exception e) {
        	factory.close(false);
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
        return msg;
	}

	@SuppressWarnings({ "deprecation", "rawtypes" })
	@Override
	public MessageBean<?> getProcessData(String ids) {
		MessageBean<List> msg = MessageBean.create(0, "success", List.class);
        try (SessionFactory factory = new SessionFactory();) {
        	List<String> idList = JSONObject.parseArray(ids, String.class);
        	HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
            List<HiddenDanger> list = mapper.queryListById("hidden_danger_history", idList);
            msg.setData(list);
        } catch (Exception e) {
        	msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
        return msg;
	}

	@SuppressWarnings({ "deprecation", "rawtypes" })
	@Override
	public MessageBean<?> getHistoryList(String code) {
		MessageBean<List> msg = MessageBean.create(0, "success", List.class);
        try (SessionFactory factory = new SessionFactory()) {
        	HiddenDangerMapper mapper = factory.getMapper(HiddenDangerMapper.class);
            List<HiddenDanger> list = mapper.queryListByCode(code);
            msg.setData(list);
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
        return msg;
	}

	@SuppressWarnings({ "resource", "unused", "unchecked" })
	@Override
	public MessageBean<?> importExcel(StaffBean user, String title, String note,MultipartFile file) {
		MessageBean<?> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, void.class);
		if(file == null){
			msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
			return msg;
		}
		try{
			//上传文件
			String url = clientWrapper.uploadFile(file);
            String fileName = file.getOriginalFilename();
            String filePath = url + "#" + fileName;
			InputStream inputStream = file.getInputStream();
			
			new Thread(){
				@Override
				public void run(){
					try {
						Date date = new Date();
						List<HiddenDanger> list = new ArrayList<HiddenDanger>();
						XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
						XSSFSheet sheet = workbook.getSheetAt(0);
						if (sheet == null) {
							return;
						}
						
						for (int rowNum = 2; rowNum <= sheet.getLastRowNum(); rowNum++) {
							HiddenDanger bean = new HiddenDanger();
							Row row = sheet.getRow(rowNum);
							if (row != null) {
								String code = getCellValue(row.getCell(0));
								String dangerTypeName = getCellValue(row.getCell(1));
								if (dangerTypeName == null) {
									continue;
								}
								String dangerTypeId = null;
								IndicationType dangerType = indicationTypeService.fetchForKey("danger_type");
								for (IndicationItems indication : dangerType.getIndicationItems()) {
					                if (indication.getName().equalsIgnoreCase(dangerTypeName)) {
					                	dangerTypeId = indication.getId();
					                }
					            }
					            if (dangerTypeId == null) {
					            	continue;
					            }
								String dangerLevelName = getCellValue(row.getCell(2));
								if (dangerLevelName == null) {
									continue;
								}
								String dangerLevelId = null;
								IndicationType dangerLevel = indicationTypeService.fetchForKey("danger_level");
								for (IndicationItems indication : dangerLevel.getIndicationItems()) {
					                if (indication.getName().equalsIgnoreCase(dangerLevelName)) {
					                	dangerLevelId = indication.getId();
					                }
					            }
								if (dangerLevelId == null) {
					            	continue;
					            }
								String firstElementName = getCellValue(row.getCell(3));
								if (firstElementName == null) {
									continue;
								}
								DictData firstElement = dataService.matchDictData("一级分类", firstElementName);
					            if (firstElement == null) {
					            	continue;
					            }
					            String firstElementId = firstElement.getId();
					            if (firstElementId == null) {
					            	continue;
					            }
								
								String secondElementName = getCellValue(row.getCell(4));
								if (secondElementName == null) {
									continue;
								}
								DictData secondElement = dataService.matchDictData("二级分类"+firstElementName, secondElementName);
					            if (secondElement == null) {
					            	continue;
					            }
					            String secondElementId = secondElement.getId();
					            if (secondElementId == null) {
					            	continue;
					            }
								String description = getCellValue(row.getCell(5));
								String precaution = getCellValue(row.getCell(6));
								String remark = getCellValue(row.getCell(7));
								bean.setCode(code);
								bean.setDangerTypeId(dangerTypeId);
								bean.setDangerLevelId(dangerLevelId);
								bean.setFirstElementId(firstElementId);
								bean.setSecondElementId(secondElementId);
								bean.setFstatusflag(0);
								bean.setDescription(description);
								bean.setPrecaution(precaution);
								bean.setRemark(remark);
								bean.setState(0);
								list.add(bean);
							} else {
								continue;
							}
						}
						MessageBean<?> saveMsg = saveDraft(list, user);
						if(saveMsg.getData() == null){
							return;
						}
						List<String> idList = (List<String>) saveMsg.getData();
						//启动流程
						Audit audit = new Audit(title, note, user.getName(), new Date());
						audit.setId(DefaultIdGenerator.getInstance().generateLongId());
						audit.setTitle(title);
						audit.setDescription(note);
						audit.setInitiatorCode(user.getCode());
						audit.setTarget(HiddenDanger.class.getName());
						audit.setSetCode(setCode);
						audit.setTemplateKey(safe_standard_hd_add);
						audit.setOperation(1);
						audit.setState(1);
						audit.setFlowType(1);
						audit.setFlowName(Immutable.ADD_HIDDEN_DANGER);
						audit.setBusinessIds(new Gson().toJson(idList));
						audit.setAttachment(filePath);
						if(!flowManagement.initFlow(user, audit, new HashMap<>())){
							delete(idList);
							msg.setCode(BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
							msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
							return;
						}
						updateFstatusflag(idList, 1);
					} catch (Exception e) {
						logger.error(e.getMessage(),e);
					}
				}
			}.start();
			return msg;
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
			msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
			return msg;
		}
	}
	
	@SuppressWarnings("deprecation")
	public void delete(List<String> idList){
		try(SessionFactory factory=new SessionFactory();){
    		HiddenDangerMapper mapper=factory.getMapper(HiddenDangerMapper.class);
    		mapper.batchDelete("hidden_danger_history", idList);
    	}catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}
	
	private String generateCode(SessionFactory factory){
		Integer count = factory.getMapper(HiddenDangerMapper.class).count(null, null, null, null, null, null, null);
		count++;
		NumberFormat nf = NumberFormat.getInstance();
		nf.setGroupingUsed(false);
		nf.setMaximumIntegerDigits(4); // 设置最大整数位数
		nf.setMinimumIntegerDigits(4); // 设置最小整数位数
		StringBuilder sb = new StringBuilder();
		sb.append("YG").append(nf.format(count));
		return sb.toString();
	}
	
	@SuppressWarnings("deprecation")
	public void updateDisposalState(List<String> idList,int disposalState){
    	try(SessionFactory factory=new SessionFactory();){
    		HiddenDangerMapper mapper=factory.getMapper(HiddenDangerMapper.class);
    		mapper.updateDisposalState(idList,disposalState);
    	}catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
    }
	
	
	/**
	 * 获取单元格的值
	 * 
	 * @param cell
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public String getCellValue(Cell cell) {
		if (cell == null)
			return "";
		if (cell.getCellTypeEnum() == CellType.STRING) {
			return cell.getStringCellValue();
		} else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if (cell.getCellTypeEnum() == CellType.FORMULA) {
			return cell.getCellFormula();
		} else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
			return String.valueOf(cell.getNumericCellValue());
		} else {
			return "";
		}
	}


	@Override
	public void reject(Audit audit, List<String> userIdList) {
		// TODO 流程驳回操作
	}

	@Override
	public void passApproval(Integer operation, Audit audit) {
		// TODO 流程提交成功操作
	}
}
